#!/bin/bash

set -u

function cmd_flash()
{
	echo -e "[DEBUG] ${FUNCNAME} $@"

	# Default to flash all partition
	local FLASH_OPTIONS=""
	local FLASH_DEV_PARTITION="mmcblk0p1"

	if [[ $# -ge 1 ]]; then
		local SUB_CMD=$1
		shift
		FLASH_OPTIONS=$@

		case ${SUB_CMD} in
			"emmc" )
				FLASH_DEV_PARTITION="mmcblk0p1"
				;;
			"nvme" )
				FLASH_DEV_PARTITION="nvme0n1p1"
				;;
			* )
				echo -e "[ERROR] Unsupport FLASH DEVICE: ${SUB_CMD}\n"
				usage
				exit 1
				;;
		esac
	fi

	local FLASH_CMD="./flash.sh ${FLASH_OPTIONS} ${JETSON_CONF} ${FLASH_DEV_PARTITION}"
	if [[ $(check_device_recovery) != "Y" ]]; then
		echo -e "[INFO] Please connect the Jetson Device to HOST, and put it into recovery mode."
		read -p "Press any key to continue ..." key

		if [[ $(check_device_recovery) != "Y" ]]; then
			echo -e "[ERROR] Jetson Board does not connect, cannot flash, exit!"
			exit 1
		fi
	fi

	echo -e "[INFO] Flash command: ${FLASH_CMD}"
	read -p "Continue to flash? (Y/n):" key
	if [[ ${key} == "n" || ${key} == "N" ]]; then
		echo -e "[INFO] Exit"
		exit 0
	fi

	cd ${L4T_TOP}
	sudo_cmd ${FLASH_CMD}
	cd - &> /dev/null
}
